package com.lm.jsch.example;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.InputStream;

public class JSchExecExample {
    public static void main(String[] args) {

        String host = "your-server-ip";
        String user = "your-username";
        String password = "your-password";

        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(user, host, 22);
            session.setPassword(password);

            // 忽略主机密钥检查
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            // 打开执行命令的通道
            ChannelExec channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand("ls -l");

            // 获取命令输出
            InputStream inputStream = channel.getInputStream();
            channel.connect();

            byte[] tmp = new byte[1024];
            while (inputStream.read(tmp) != -1) {
                System.out.print(new String(tmp));
            }

            channel.disconnect();
            session.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

